package com.wanmait.computershop.dao;

import com.wanmait.computershop.util.DBHelper;
import com.wanmait.computershop.vo.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDAO {
    public User findById(Integer id) {
        QueryRunner queryRunner = new QueryRunner();
        String sql = "select * from user where id = ?";
        try {
            User user = queryRunner.query(sql, new BeanHandler<>(User.class), id);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    //新用户注册，输入用户名和密码注册
    public void insert(String username, String userpass) {
        QueryRunner queryRunner = new QueryRunner(DBHelper.getDataSource());
        String sql = "INSERT INTO user (username, userpass) VALUES (?,?)";


        try {
            queryRunner.update(sql, username, userpass);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public User login(String username, String password) {

        QueryRunner queryRunner = new QueryRunner(DBHelper.getDataSource());
        String sql = "select * from user where username = ? and userpass = ?";

        try {
            User user = queryRunner.query(sql, new BeanHandler<>(User.class), username, password);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
